package com.sharingsperejdbc.demo.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @author wwz
 */
@Slf4j
public class CustomDBShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    private final static String CONST = "000";

    private final static String DB = "ds";
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        Long value = preciseShardingValue.getValue();
        // 真实节点
        collection.stream().forEach((item) -> {
            log.info("[存在的库<{}>]", item);
        });
        log.info("[表名<{}> 列名<{}>]", preciseShardingValue.getLogicTableName(), preciseShardingValue.getColumnName());
        if(value != null){
            String v = value.toString();
            int index = v.lastIndexOf(CONST);
            if(index >= 0){
                v = v.substring(index-1,index);
            }
            log.info("[分库确定的<{}>]", DB.concat(v));
            for (String each : collection) {
                if (each.equals(DB.concat(v))) {
                    return each;
                }
            }
        }
        throw new IllegalArgumentException();
    }
}
